<?php
/**
 * 公共类登录限制与学员老师权限区分
 */
namespace app\controllers;

use Yii;
use yii\helpers\Url;

class CommonController extends \yii\web\Controller
{

    public function init(){
        //判断是否登录
        if(Yii::$app->user->isGuest){
            Yii::$app->getSession()->setFlash('error', '还没有登录，先登录后再访问');
            $this->redirect(['/site/login']);
            return false;
        }else{
            $url = Yii::$app->request->get()['r'];

            if(Yii::$app->user->identity->roles == '老师'){
                $pass = $this->_teacherRule($url);
                if(!$pass){
                    Yii::$app->getSession()->setFlash('error', '你没有权限访问该页面');
                    $this->redirect(['/user/index']);
                    return false;
                }else{
                    return true;
                }
            }elseif(Yii::$app->user->identity->roles == '学员'){
                $pass = $this->_studentsRule($url);
                if(!$pass){
                    Yii::$app->getSession()->setFlash('error', '你没有权限访问该页面');
                    $this->redirect(['/students/view']);
                    return false;
                }else{
                    return true;
                }
            }

        }

    }

    protected function _teacherRule($url){
        $urls = array(
            'site/index',
            'user/index',
            'user/create',
            'user/view',
            'user/update',
            'user/delete',
            'attendance/index',
            'attendance/create',
            'attendance/add',
            'homework/index',
            'homework/create',
            'homework/add',
            'test/index',
            'test/create',
            'test/add',
            'students/attendance',
            'students/homework',
            'students/test',
            'students/class',
            'classitem/create',
            'classitem/update',
            'classitem/index',
            'classitem/view',
        );
        if(in_array($url, $urls)){
            return true;
        }else{
            return false;
        }
    }

    protected function _studentsRule($url){
        $urls = array(
            'site/index',
            'students/view',
            'students/update',
            'students/attendance',
            'students/homework',
            'students/test',
            'students/class',
        );
        if(in_array($url, $urls)){
            return true;
        }else{
            return false;
        }
    }

}
